//============================================================================
// Name        : DoTA.cpp
// Author      : Jaime Pavlich-Mariscal
// Version     :
// Copyright   : 
// Description : Doppler Tomogram Analyzer
//============================================================================
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <libconfig.h++>
#include <EXTERN.h>
#include <perl.h>


#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include "ShellCommand.h"
using namespace std;
using namespace libconfig;

vector<string> getFiles(string dir) {
	vector<string> files;
	DIR *dp;
	struct dirent *dirp;
	if ((dp = opendir(dir.c_str())) == NULL) {
		cerr << "Error(" << errno << ") opening " << dir << endl;
		return files;
	}

	while ((dirp = readdir(dp)) != NULL) {
		files.push_back(string(dirp->d_name));
	}
	closedir(dp);
	sort(files.begin(), files.end());
	return files;
}

bool endsWith(std::string const &str, std::string const &endString) {
	if (str.length() > endString.length()) {
		return (0 == str.compare(str.length() - endString.length(),
				endString.length(), endString));
	} else {
		return false;
	}
}

static PerlInterpreter *my_perl;

int main(int argc, char** argv) {
	char *embedding[] = { "", "etc/dota.config.pl" };
	int exitStat;

	my_perl = perl_alloc();
	perl_construct( my_perl);

	exitStat = perl_parse(my_perl, NULL, 3, embedding, NULL);
	if (!exitStat) {
		exitStat = perl_run(my_perl);
	}


	/** Treat $a as a string **/
	printf("path = %s\n", SvPV(perl_get_sv("path", FALSE), PL_na));


	/*
	 Config c;
	 c.readFile("dota.config");

	 string doppler_path;
	 string dataset_path;
	 string output_path;
	 string start_image;
	 string makimg_cmd;
	 string optscl_cmd;
	 string memit_cmd;
	 c.lookupValue("doppler.path", doppler_path);
	 c.lookupValue("doppler.output_path", output_path);
	 c.lookupValue("doppler.start_image", start_image);
	 c.lookupValue("doppler.dataset_path", dataset_path);
	 c.lookupValue("doppler.makimg_cmd", makimg_cmd);
	 c.lookupValue("doppler.optscl_cmd", optscl_cmd);
	 c.lookupValue("doppler.memit_cmd", memit_cmd);

	 vector<string> files = getFiles(dataset_path);

	 for (vector<string>::iterator file = files.begin(); file != files.end(); file++) {
	 if (endsWith(*file, string(".sdf"))) {

	 string str = doppler_path + "/" + makimg_cmd + " IMAGE="
	 + output_path + "/" + start_image;
	 exec(str);

	 str = doppler_path + "/" + optscl_cmd + " IMAGE=" + output_path
	 + "/" + start_image + " DATA=" + dataset_path + "/" + *file;
	 exec(str);

	 double X2aim = 10.0;
	 for (int i=0; i<18; i++) {

	 }
	 }
	 } */

	perl_destruct(my_perl);
	perl_free(my_perl);

	return 0;
}
